<template>
  <div class="form-page">
    <Card :bordered="false" :dis-hover="true">
      <p slot="title" style="color: #666;">
        <span
          class="iconfont icon-changyongtubiao-xianxingdaochu-zhuanqu-"
          style="font-size: 20px;"
        ></span> 推送信息
      </p>
      <p slot="extra" style="color: #999;font-size: 12px;">
        <label style="color: #FF3B30;">*</label> 为必填
      </p>
      <Form ref="formModel" :rules="ruleValidate" :model="bloc.form" :label-width="150" label-position="right">
        <FormItem label="推送标题:" prop="title" required>
          <Input Radiotype="text" v-model="bloc.form.title" placeholder="请填写推送标题" style="width: 400px;height: 40px;"/>
        </FormItem>
        <FormItem label="推送平台:" prop="pushOS" required>
          <Select style="width: 415px" multiple v-model="bloc.form.pushOS" placeholder="请填写推送平台">
            <Option value="IOS">IOS</Option>
            <Option value="ANDROID">ANDROID</Option>
            <Option value="THINGS">THINGS</Option>
          </Select>
        </FormItem>
        <FormItem label="推送方式:" prop="pushType" required>
          <Select style="width: 415px" v-model="bloc.form.pushType" placeholder="请选择推送方式">
            <Option value="TIMING">定时推送</Option>
            <Option value="REAL_TIME">实时推送</Option>
          </Select>
          <DatePicker
            v-if="bloc.form.pushType === 'TIMING'"
            type="datetime"
            placeholder="推送时间"
            v-model="bloc.form.pushTime"
            style="width: 200px;margin-left: 10px"></DatePicker>
        </FormItem>
        <FormItem label="目标类型:" prop="targetType" required>
          <Select style="width: 415px" v-model="bloc.form.targetType" placeholder="请选择目标类型">
            <Option value="TEXT">纯文本</Option>
            <Option value="EXTERNAL">外链</Option>
            <Option value="INTERNAL">资讯</Option>
          </Select>
        </FormItem>
        <FormItem label="目标链接:" prop="targetLinks" required>
          <Input type="text" v-model="bloc.form.targetLinks" placeholder="请填写目标链接" style="width: 400px"/>
        </FormItem>
        <FormItem label="消息缩列图:">
          <div class="demo-upload-list mar-left" v-for="(item, index) in fileList" :key="index">
            <template v-if="item.status === 'finished'">
              <img :src="item.url">
              <div class="demo-upload-list-cover">
                <Icon type="ios-eye-outline" @click.native="handleView(item.url)"></Icon>
                <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
              </div>
            </template>
            <template v-else>
              <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
            </template>
          </div>
          <Upload
            :class="{'mar-left': fileList.length <= 0}"
            ref="upload"
            :show-upload-list="false"
            :format="['jpg','jpeg','png']"
            :max-size="2048"
            :headers="uploadHeaders"
            :action="uploadAction"
            :on-success="handleSuccess"
            :on-format-error="handleFormatError"
            :on-exceeded-size="handleMaxSize"
            multiple
            type="drag"
            style="display: inline-block;width:58px;">
            <div style="width: 58px;height:58px;line-height: 58px;">
              <Icon type="ios-camera" size="20"></Icon>
            </div>
          </Upload>
          <Modal title="View Image" v-model="visible">
            <img :src="imgUrl" v-if="visible" style="width: 100%">
          </Modal>
        </FormItem>
        <FormItem label="自定义推送用户:">
          <Input v-model="bloc.form.targetAccounts[0]" :rows="4" maxlength="300" show-word-limit type="textarea"
                 placeholder="请填写推送用户..."
                 style="width: 400px"/>
        </FormItem>
        <FormItem label="推送内容:" prop="body" required>
          <Input type="textarea" :rows="4" v-model="bloc.form.body" maxlength="300" show-word-limit
                 placeholder="请填写推送内容..."
                 style="width: 400px;"/>
        </FormItem>
      </Form>
      <div style="margin: 20px 0px 35px 25px;">
        <router-link :to="{ path: '/news'}">
          <Button style="width: 100px;height: 40px;">返回</Button>
        </router-link>
        <Button type="primary" style="margin-left: 30px;width: 100px;height: 40px;" @click="handleOk('formModel')"
                :loading="btnload.loading"
                :disabled="bloc.isDetail">保存
        </Button>
      </div>

    </Card>
  </div>
</template>

<script lang="ts">
  import {Component, Vue} from 'vue-property-decorator';
  import {Route} from 'vue-router';
  import {FormBloc} from '@/view/news/FormBloc';
  import {baseUrl} from '@/base/Request';
  import {store} from '@/store/Store';
  import {Loading} from '@/base/Loading';
  import {isEmpty} from '@/base/util/Strings';
  import {getValidateMaxString} from '@/base/util/Validate';

  @Component
  export default class extends Vue {
    beforeRouteEnter(to: Route, from: Route, next: (vm: any) => void) {
      next(vm => {
        vm.bloc.isDetail = vm.$route.query.detail === '1';
        if (!vm.isAdd) vm.bloc.load(vm.idx);
      });
    }

    get isAdd() {
      return !this.idx;
    }

    get idx() {
      return Number(this.$route.params.id);
    }

    get uploadAction() {
      return `${baseUrl}/api/upload/image`;
    }

    get uploadHeaders() {
      return {
        'Authorization': 'Bearer ' + store.state.auth.accessToken
      };
    };

    get fileList() {
      return this.bloc.form.images.map(x => {
        return {'name': 'name', 'url': x, 'status': 'finished'};
      });
    }

    bloc: FormBloc = new FormBloc();
    btnload = new Loading();
    imgUrl = '';
    visible = false;
    ruleValidate = {
      title: [
        {
          validator: (rule, value, callback) => {
            if (isEmpty(value)) callback(new Error('推送标题不能为空'));
            else if (getValidateMaxString(15, value)) callback(new Error('推送标题的长度不能超过15'));
            else callback()
          },
          trigger: 'blur'
        }
      ],
      pushOS: [
        {
          validator: (rule, value, callback) => {
            if (value.length <= 0) {
              callback(new Error('请至少选择一个推送平台'));
            } else {
              callback();
            }
          },
          trigger: 'blur'
        }
      ],
      pushType: [
        {required: true, message: '请填写推送标题', trigger: 'blur'}
      ],
      targetType: [
        {required: true, message: '请选择目标类型', trigger: 'blur'}
      ],
      targetLinks: [
        {required: true, message: '请填写目标链接', trigger: 'blur'}
      ],
      body: [
        {required: true, message: '请填写推送内容', trigger: 'blur'}
      ]
    };

    handleView(url) {
      this.imgUrl = url;
      this.visible = true;
    }

    handleRemove(file) {
      this.bloc.form.images.splice(this.bloc.form.images.indexOf(file), 1);
    }

    handleSuccess(res, file) {
      this.bloc.form.images.push(res.data[0]);
    }

    handleFormatError(file) {
      this.$Notice.warning({
        title: 'The file format is incorrect',
        desc: 'File format of ' + file.name + ' is incorrect, please select jpg or png.'
      });
    }

    handleMaxSize(file) {
      this.$Notice.warning({
        title: 'Exceeding file size limit',
        desc: 'File is too large, no more than 2M.'
      });
    }

    handleCancel() {
      this.$router.push({path: `/news`});
    }

    handleOk(name) {
      if (this.bloc.form.pushType === 'TIMING' && isEmpty(this.bloc.form.pushTime)) {
        this.$Message.error('推送时间不能为空');
        return;
      }
      const formRef: any = this.$refs[name];
      formRef.validate((valid) => {
        if (valid) {
          this.saveFn();
        }
      });
    }

    saveFn() {
      this.btnload.loading = true;
      if (this.bloc.form.pushType === 'REAL_TIME') this.bloc.form.pushTime = new Date() + '';
      const parmas = this.isAdd ? '' : this.idx;
      // this.bloc.save(parmas).then(res => {
      //   this.$Message.success('保存成功');
      //   this.btnload.loading = false;
      //   this.handleCancel();
      // }).catch(err => {
      //   this.btnload.loading = false;
      //   this.$Message.error('保存失败');
      //   console.log('出错啦::::', err);
      // });
    }
  }
</script>

<style lang="less" scoped>
  .mar-left {
    margin-left: 15px;
  }
</style>
